<script type="text/html" template lay-done="layui.data.formFillUpdatedone(d);">
    <div class="formFill-transmit-content">
        <div class="layui-card">
            <div class="layui-card-body">
                <form class="layui-form" lay-filter="formFill-transmit-form">
                    <div class="form-transmit-condition">
                        <!-- <div class="layui-form-item">
                            <div class="layui-inline">
                                <label class="layui-form-label">是否复核：</label>
                                <div class="layui-input-inline" style="width:80px;">
                                    <input type="checkbox" name="switch" lay-skin="switch" lay-text="是|否" lay-filter="switchTest" class="layui-audit-switch">
                                </div>
                            </div>
                            <div class="layui-inline">
                                <div class="review-content">
                                    <label class="layui-form-label" style="width:100px;">附加复核人：</label>
                                    {{# if(d.params.review && d.params.review === '1'){ }}
                                        <div class="review-value-box T-event" data-target="to-review">
                                            {{# layui.each(d.params.wadduserMsg, function(index, item){ }}
                                                <span usercode="{{item.user_code}}" certcode="{{item.cert_code}}">{{item.userName}}</span>
                                            {{# }) }}
                                        </div>
                                    {{# }else{ }}
                                        <div class="review-value-box layui-bg-gray T-event" data-target="to-review">
                                            {{# layui.each(d.params.wadduserMsg, function(index, item){ }}
                                                <span usercode="{{item.user_code}" certcode="{{item.cert_code}}">{{item.userName}}</span>
                                            {{# }) }}
                                        </div>
                                    {{# } }}
                                </div>
                            </div>
                        </div> -->
                        <div class="special-content">
                            <div class="special-value">
                                <button type="button" class="layui-btn layui-btn-xs T-event" data-target="unit"><i class="layui-icon">&#xe608;</i>转发单位</button>
                                <div class="check-value-box formFill-update-department">
                                        {{#
                                            if(d.params.deptMsg) {
                                                var exitDep = d.params.deptMsg.length ? d.params.deptMsg : [];
                                                layui.each(exitDep, function(index,item) {
                                        }}
                                            <div class="unit-content">
                                                {{item.writeusername}}
                                                <i class="icon-del-unit T-event" data-target="delUnit" data-deptid='{{item.dataid}}'></i>
                                            </div>
                                        {{#
                                                })
                                            }
                                        }}
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="iframeContent">
                        <iframe id="mainFormIframe" class="formFill-updateHtml-form" src="./bindForm/main.html" frameborder="0"></iframe>
                    </div>
                    <div class="buttons-area">
                        {{#  if(d.params.transmitState && d.params.transmitState === "已转发"){ }}
                            <button type="button" class="T-event layui-btn lay-submit layui-btn-disabled">任务已转发</button>
                        {{#  } else { }}
                            <button type="button" class="T-event layui-btn lay-submit" lay-filter="form-submit" data-target="add">任务转发</button>
                        {{#  } }}  
                    </div>
                    <textarea name="zf" id="zfState" cols="30" rows="10" style="display: none;">
                            {{d.params.zf}}
                    </textarea>
                </form>
            </div>
        </div>
    </div>
</script>

<style>
    .special-content {
        width: 100%;
        margin-bottom: 15px;
    }   
    .special-key {
        overflow: hidden;
        width: 110px;
        float: left;
        padding: 9px 15px 9px 0;
        text-align: center;
    }
    .special-value {
        overflow: hidden;
        border: 1px solid #C5C5C5;
    }
    .check-value-box {
        height: 100%;
        overflow-y: auto;
        padding: 4px 6px;
    }
    .formFill-updateHtml-form{
        width: 100%;
        height: 550px;
        margin-bottom: 40px;
    }
    .buttons-area {
        position: absolute;
        bottom: 0px;
        left: 0px;
        width: 100%;
        height: 40px;
        text-align: center;
        margin-top: 10px;
    }
    .unit-content{
        display: inline-block;
        padding: 0 31px 0 5px;
        margin-bottom: 2px;
        background-color: #DCE7F4;
        position: relative;
        height: 25px;
        line-height: 25px;
    }
    .unit-content a:hover{
        text-decoration: underline;
    }
    .unit-content:hover .icon-del-unit{
        visibility: visible;
        background:  url('/src/style/res/formFill/unit-del-hover.png') no-repeat center center;
    }
    .unit-content .icon-del-unit {
        position: absolute;
        width: 16px;
        height: 16px;
        top: 4px;
        right: 8px;
        background:  url('/src/style/res/formFill/unit-del.png') no-repeat center center;
        cursor: pointer;
    }
    .layui-layer{
        border-radius: 5px;
        overflow: hidden;
    }
    .layui-layer-setwin{
        top: 10px;
        right: 11px;
    }
    .layui-layer-setwin .layui-layer-close1{
        background-position: 0 0;
    }
    .layui-layer-setwin a{
        width: 18px;
        height: 18px;
        margin: 0;
        background: url('/src/style/res/formFill/layer-close.png') no-repeat center center;
        background-position: 0px 0px;
    }
    .formFill-transmit-content .layui-form{
        background-color: #F2F7FD;
        padding: 12px 12px 0 12px;
    }
    .form-transmit-condition{
        height: 60px;
        border: 1px solid #D2D2D2;
        border-radius: 4px;
        padding: 18px 28px 0 28px;
        background-color: #FFFFFF;
    }
    .formFill-transmit-content .layui-card-body{
        padding: 0 12px 0 12px;
        margin: 0;
        background:linear-gradient(137deg,rgba(29,91,174,1),rgba(81,175,188,1));
    }
    .form-transmit-condition .layui-form-label{
        padding: 0;
        height: 40px;
        line-height: 40px;
        text-align: center;
    }
    .form-transmit-condition .layui-input-block{
        margin-left: 80px;
    }
    .form-transmit-condition .layui-form-item, .special-value{
        height: 35px;
        border-radius:6px;
    }
    .form-transmit-condition .layui-form-switch{
        width: 60px;
        height: 24px;
        line-height: 23px;
    }
    .special-value button{
        float: left;
        padding: 0 7px;
        height: 35px;
        line-height: 35px;
        background-color: #2669B1;
        border-radius: 4px;
    }
    .form-transmit-condition .layui-form-item, .special-content{
        margin-bottom: 21px;
    }
    .lay-submit{
        background-color: #2669B1;
    }
    .form-transmit-condition .layui-form-onswitch {
        border-color: #2669B1;
        background-color: #2669B1;
    }
    .to-review{
        display: inline-block;
        line-height: 40px;
    }
    .layui-layer-page .layui-layer-content{
        overflow: auto;
        background-color: #FFFFFF;
    }
    .review-value-box{
        display: inline-block;
        width: 360px;
        height: 35px;
        line-height: 20px;
        border-radius: 6px;
        margin-left: 10px;
        overflow-y: scroll;
        border: 1px solid #cccccc;
    }
</style>

<!-- 转发单位模板 -->
<script type="text/html" id="temporaryselectunitTpl">
    {{# layui.each(d, function(index, item) {  }}
        <div class="unit-content">
            <a href="javascript:void(0)">{{item.writeusername}}</a>
            <i class="icon-del-unit T-event" data-target="delUnit" data-deptid='{{item.dataid}}'></i>
        </div>
    {{#  }) }}
</script>
<!-- 转发群组模板 -->
<script type="text/html" id="temporaryselectgroupTpl">
    {{# layui.each(d, function(index, item) {  }}
        <div class="unit-content">
            <a href="javascript:void(0)">{{item.writeusername}}</a>
            <i class="icon-del-unit T-event" data-target="delGroup" data-deptid='{{item.dept_id}}'></i>
        </div>
    {{#  }) }}
</script>

<script type="text/javascript">
    layui.data.formFillUpdatedone = function(d){
        layui.use(['admin', 'form', 'laydate', 'upload', 'tools', 'table'], function(){
            var $ = layui.$,
			admin = layui.admin,
			view = layui.view,
			element = layui.element,
			layer = layui.layer,
			laydate = layui.laydate,
			laytpl = layui.laytpl,
			upload = layui.upload,
			tools = layui.tools,
			filenames = [],
            form = layui.form,
            table = layui.table;
        
            var selectDep = d.params.deptMsg || [], //页面传递数据
                selectGrp = d.params.groupMsg || [],
                selectSef = d.params.selfMsg || [],
                validChk = 0, //复核开关状态
                auditChk = 0, //审核开关状态
                tholdName = [], //当前表头修改前的值
                switchKey = parseInt(d.params.review) || 0;
            

        form.render(null, 'formFill-transmit-form');

        getexitForm();
        
        //监听复核、审核按钮
        form.on('switch(switchTest)', function(data){
            var valid = this.checked ? 1 : 0;
            window.validChk = valid;
            if(data.elem.checked){
				switchKey = 1;
				$('.review-value-box').removeClass('layui-bg-gray');
			}else{
				switchKey = 0;
				$('.review-value-box').addClass('layui-bg-gray');
			}
        })

        form.on('switch(switchAudit)', function(data){
            var audit = this.checked ? 1 : 0;
            window.auditChk = audit;
        });

        //页面按钮点击事件
        $('.formFill-transmit-content').delegate('.T-event', 'click', function(){ 
            var target = $(this).data('target');
            if(target == 'unit'){
                layer.open({
                    id: 'formFill-unithtml',
                    title:'<i class="formFill-icon"></i><span style="color:#FFF;">转发单位</span>',
                    offset: '20px',
                    type: 1,
                    shadeClose: true,
                    area: ['450px', '650px'],
                    success: function(lay, index) {
                        view(this.id).render('./fill/transmitDep/unit', {
                            exitDep: selectDep,
                            taskid: d.params.taskid
                        }).done(function() { 
                            $(lay).on('click', '.T-confirm', function() {
                                selectDep = JSON.parse($(lay).find('.data-dep-container').val());
                                var depNameStr = selectDep;
                                var getTpl = temporaryselectunitTpl.innerHTML;
                                var $tplC = $('.formFill-update-department');
                                laytpl(getTpl).render(depNameStr, function(html){
                                    $tplC.html(html);
                                });
                                layer.close(index);
                            });
                        });
                    }
				});
            }else if(target == 'group'){
                layer.open({
						id: 'formFill-grouphtml',
						title:'<i class="formFill-icon"></i><span style="color:#FFF;">转发群组</span>',
						offset: '20px',
						type: 1,
						shadeClose: true,
						area: ['450px', '650px'],
						success: function(lay, index) {
							view(this.id).render('./fill/transmitDep/group', {
								exGgrp: selectGrp
							}).done(function() {
								$(lay).on('click', '.T-confirm', function() {
									selectGrp = JSON.parse($(lay).find('.data-group-container').val());
                                    var depNameStr = selectGrp;
									var getTpl = temporaryselectgroupTpl.innerHTML;
									var $tplC =$('.formFill-update-group');
									laytpl(getTpl).render(depNameStr, function(html){
										$tplC.html(html);
									});
									layer.close(index);
								});
							});
						}
				});
            }else if(target == 'add'){ //任务转发
                var deptMsg = [], //转发单位
                    groupMsg = [], //转发群组
                    persentMsg = [], //本单位转发
                    formMsg = [],
                    reviewMan = [],
					reviewApply = $('.review-value-box span'); 
                var Iframe = document.getElementById('mainFormIframe').contentWindow,
                    selectUl = Iframe.document.querySelector('.select-nodes-list').children,
                    selectList = selectUl[0].children,
                    delFormMsg = Iframe.document.querySelector('#del-form-container').innerText;

                $.each(selectList, function(index, item){
						item.click();
						var model = item.getAttribute('data-model');
						if(model == 'insert'){
							var html = item.getAttribute('data-html'),
								params= Iframe.reloadTab(html, 'copy');
							params.tablename = '';
							params.form_id = '';
							params.id = '';
							formMsg.push(params);
						}else if(model == 'choose' || model == 'normal'){
							var html = item.getAttribute('data-html'),
								choParams = Iframe.reloadTab(html, 'copy');
							choParams.model = model;
							choParams.tablename = item.getAttribute('data-tablename');
							choParams.form_id = item.getAttribute('data-formid');
                            choParams.id = model == 'normal' ? item.getAttribute('id') : '';
							formMsg.push(choParams);
						}
                });
                console.log(formMsg,"formMsg")                  
                $.each(selectDep, function(index, item){
                    var obj = new Object();
                    obj.belongto = d.params.writeid;
                    obj.dataid = item.dept_id;
                    obj.dept_code = item.dept_code;
                    obj.writeusername = item.writeusername;
                    deptMsg.push(obj);
                });
                                    
                $.each(selectGrp, function(index, item){
                    var obj = new Object();
                    obj.belongto = d.params.writeid;
                    obj.dataid = item.dept_id;
                    obj.writeusername = item.writeusername;
                    groupMsg.push(obj);
                })
                //复核人信息
				if(reviewApply){
					$.each(reviewApply, function(index, item){
						reviewMan.push({ user_code: item.getAttribute('usercode'), userName: item.innerText, cert_code: item.getAttribute('certcode') })
					})
                } 
                if(deptMsg.length > 0){
                    admin.req({
                        url: 'myapi/DC/api/rest/web/custom/addTransData',
                        type: 'post',
                        data: {
                            taskid: d.params.taskid,
                            jsonId: d.params.jsonId,
                            review: 1,
                            audit: auditChk,
                            link: d.params.link,
                            writeid: d.params.writeid,
                            deptMsg: JSON.stringify(deptMsg),
                            groupMsg: JSON.stringify(groupMsg),
                            formMsg: JSON.stringify(formMsg),
                            wadduserMsg: JSON.stringify(reviewMan)
                        },
                        success: function(res){
                            if(res.retcode == 0){
                                $('#zfState').val('true');
                                layer.msg('任务转发成功', {time: 1000});
                                layer.closeAll('page'); //关闭所有页面层
                            }else{
                                layer.msg(res.retmsg, {time: 1000});
                            }
                        },
                        error:function(){
                            console.log('接口失败！')
                        }
                    }) 
                }else{
                    layer.msg('请选择转发单位', {time: 1000});
                }
            }else if(target == 'delUnit'){
                var depid = $(this).data('deptid');
                delArr();
				function delArr() {
					var filterDep = [];
					$.each(selectDep, function(index, item) {
						if(selectDep[index].dataid !== depid) {
							filterDep.push(selectDep[index]);
						}
					});
					selectDep = filterDep;
					var getTpl = temporaryselectunitTpl.innerHTML;
					var $tplC = $('.formFill-update-department');
					laytpl(getTpl).render(filterDep, function(html){
                        $tplC.html(html);
                    })
				}
            }else if(target == 'delGroup'){
                var depid = $(this).data('deptid');
                delGrp();
                function delGrp(){
                    var filterGrp = [];
                    $.each(selectGrp, function(index, item){
                        if(item.dept_id !== depid){
                            filterGrp.push(item);
                        }
                    });
                    selectGrp = filterGrp;
                    var getGrp = temporaryselectgroupTpl.innerHTML;
                    var $grpC = $('.formFill-update-group');
                    laytpl(getGrp).render(filterGrp, function(html){
                        $grpC.html(html);
                    })
                }
            }else if(target == 'to-review'){
                var text = $(this).siblings('label').text(),
						reviewUrl = null,
						selectPerson = $('.review-value-box span'),
						selectIds = [];
					if(switchKey == 0){
						return false
					}else{
                        text == '附加复核人：' ? reviewUrl = './task/temporary/addPerson' : reviewUrl = './task/temporary/pullPerson';
						if(selectPerson){
							layui.each(selectPerson, function(index, item){
								selectIds.push({ user_code: item.getAttribute('usercode'), userName: item.innerText});
							});
						}
						layer.open({
							id: 'temporary-reviewHtml',
							title: '<i class="formFill-icon"></i><span style="color:#FFF;">'+text+'</span>',
							type: 1,
							offset: '20px',
							shadeClose: true,
							area: ['570px', '650px'],
							success: function(lay, index){
								view(this.id).render(reviewUrl, {
									checkIds: selectIds || []
								}).done(function() {
									$(lay).on('click', '.T-confirm', function() {
										if(text == "附加复核人："){
                                            var selectReview = $(lay).find('.check-value-box .unit-content'),
                                                $eachman = '';
                                            $.each(selectReview, function(index, item){
                                                var usercode = item.querySelector('.del-tag').getAttribute('data-usercode'),
                                                    certcode = item.querySelector('.del-tag').getAttribute('data-certcode'),
                                                    deptname = item.querySelector('.del-tag').getAttribute('data-deptnme'),
                                                    phone = item.querySelector('.del-tag').getAttribute('data-phone'),
                                                    email = item.querySelector('.del-tag').getAttribute('data-email'),
                                                    username = item.querySelector('a').innerText;
                                                $eachman += '<span usercode="'+usercode+'" certcode="'+certcode+'" deptname="'+deptname+'" phone="'+phone+'" email="'+email+'">'+username+'</span>、';
                                            })
                                            $('.review-value-box').html($eachman);
										}else{
											var selectAudit = JSON.parse($(lay).find('.data-audit-container').val());
											$('.audit-value-box').html(JSON.stringify(selectAudit.join(',')).replace(/"/g, ''));
										}
										layer.close(index);
									});
								});
							}
						})
					}
            }
        })

        //处理表单信息
        function getFormMsg(formHtml, baseName, baseId, choose){
            if (formHtml) {
                var template = document.createElement('div');
                template.innerHTML = formHtml;

                var tableTitle = template.querySelector('caption'); 
                if (tableTitle) {
                    var tablename = template.querySelector('caption').innerText; //表单名称
                    var formId = template.querySelector('table').getAttribute('id'); //表格id
                    if (tablename) {
                        var ths = template.querySelectorAll('.firstRow th');
                        var property = new Object();
                        var grid = [];
                        var thnewName = [];
                        if (ths.length > 0) {
                            for (var i = 0; i < ths.length; i++) {
                                var obj = new Object();
                                obj.form_typeid = formId; //字段所属表格或表单id
                                obj.fieldstate = '1'; //字段状态  正常使用为1,被删除为0
                                var text = ths[i].innerText; //字段中文名称
                                thnewName.push(text);
                                var colId = ths[i].getAttribute('id'); //字段英文名称
                                if (text) obj.fieldname = text;
                                if (colId) obj.fieldenglish = colId;
                                var sort = ths[i].getAttribute('table_sort');
                                var query = ths[i].getAttribute('query');
                                var sum = ths[i].getAttribute('sum');
                                var average = ths[i].getAttribute('average');
                                var count = ths[i].getAttribute('count');
                                var colSum = ths[i].getAttribute('col_sum');
                                var colAverage = ths[i].getAttribute('col_average');
                                var colCount = ths[i].getAttribute('col_count');
                                var dataType = ths[i].getAttribute('data_type'); //字段类型
                                var dataLength = ths[i].getAttribute('data_length'); //字段长度
                                var isFill = ths[i].getAttribute('isfill'); //必填
                                var thModel = ths[i].getAttribute('model'); //内层model属性
                                if (sort) obj.sortno = sort //排序
                                else {obj.sortno = 'null'};
                                if (dataLength) obj.length = dataLength; //字段长度
                                if (query) obj.queryno = query; //查询
                                if (average == '1' || sum == '1' || count == '1' || colSum ==
                                    '1' || colAverage == '1' || colCount == '1') obj.stacno =
                                    '1';
                                else obj.stacno = '0';
                                if (dataType) obj.datatype = dataType;
                                if (isFill) obj.nonull = isFill;
                                if(thModel) obj.model = thModel;
                                grid.push(obj);
                            }
                        }
                        var tableModel = template.querySelector('table').getAttribute('model'); //外层model属性
                        property.formname = tablename;
                        property.html = formHtml;
                        if(choose){
                            property.model = choose;
                        }else{
                            property.model = tableModel;
                        }
                        property.grid = JSON.stringify(grid); //将grid数组转换成字符串
                        if(tableModel != 'insert') {
                            property.tablename = baseName;
                            property.id = baseId;
                        };
                        return property;
                    } else {
                        layer.msg('表单名称不能为空', {time: 1000});
                        return false;
                    }
                } else {
                    layer.msg('请配置表单名称行', {time: 1000})
                    return false;
                }

            } else {
                layer.alert('表单内容不能为空', {time: 1000});
                return false;
            }
        }

        //处理表头内容属性改变时状态设置
        function setUptModel(a, b, template){
            var table = template.querySelector('table');
            var ths = table.querySelectorAll('th');
            var oldModel = table.getAttribute('model');
            //判断两个数组相等
            var flag = true;
            if(!(a instanceof Array) || !(b instanceof Array)) flag = false;
            if(a.length != b.length) flag = false;
            for(var i = 0, len = b.length; i < len; i++){
                if(a.indexOf(b[i]) == -1 && b.indexOf(a[i]) == -1 && ths[i].getAttribute('model') == 'normal') {
                    flag = false;
                    ths[i].setAttribute('model', 'update');  //当th表头值改变该列为update
                }
            }
            if(flag == false && oldModel == 'normal'){ 
                table.setAttribute('model', 'update'); //当th表头值改变时外层也为update
                var newDiv = document.createElement('div');
                newDiv.innerHTML = template;
                leipiEditor.setContent(template.innerHTML);
            }
        }

        //加载编辑时已选择的表单
        function getexitForm(){
			var mainIframe = document.getElementById('mainFormIframe');
			$(mainIframe).load(function(){
                var iContent = mainIframe.contentWindow;
				if(d.params.formMsg && d.params.formMsg.length > 0){
					var formContanier = iContent.document.querySelector('.select-nodes-list ul'),
					    chooseNodes = d.params.formMsg,
					    lihtml = '';
					if(chooseNodes && chooseNodes.length > 0){
						for(var i = 0; i < chooseNodes.length; i++){
                            var del = chooseNodes[i].del;
                            if(del == '0'){
                                lihtml += "<li data-model='normal' title='"+chooseNodes[i].formname+"' data-select='1' id='"+chooseNodes[i].id+"' del='"+chooseNodes[i].del+"' data-tablename='"+chooseNodes[i].tablename+"' data-formid='"+chooseNodes[i].form_id+"'  data-html='"+chooseNodes[i].html+"'><span>"+chooseNodes[i].formname+"</span></li>"
                            }else{
                                lihtml += "<li data-model='normal' title='"+chooseNodes[i].formname+"' id='"+chooseNodes[i].id+"' del='"+chooseNodes[i].del+"' data-tablename='"+chooseNodes[i].tablename+"' data-formid='"+chooseNodes[i].form_id+"'  data-html='"+chooseNodes[i].html+"'><span>"+chooseNodes[i].formname+"</span><i class='layui-icon layui-icon-close-fill T-btn' data-target='del-form'></i></li>"
                            }
						}
						formContanier.innerHTML = lihtml;
						var firstLi = formContanier.querySelector('li:first-of-type');
						firstLi.click();
					}
				}

                //表单预览
				$('#mainFormIframe').contents().find('#preview').click(function(){
                    var template = document.createElement('div'),
                        formContent = iContent.leipiEditor.getContent(),
                        selectNode = iContent.document.querySelector('.liactive');
                    template.innerHTML = formContent;
                    if(formContent){
                        var	cols = iContent.leipiFormDesign.getCols(template);
                        layer.open({
                            id: 'formView',
                            title:'<i class="formFill-icon"></i><span style="color:#FFF;">表单预览</span>',
                            offset: '50px',
                            type: 1,
                            shadeClose: true,
                            area: ['1250px', '550px'],
                            success: function(lay){
                                view(this.id).render('./fill/components/formView',{cols: cols, formname: selectNode.innerText});
                            }
                        });
                    }else{
                        layer.msg('请选择表单预览', {time: 1500});
                    }
				})


			})
        }

    })
}
</script>